package com.javaee.controller.admin;


import com.javaee.BeforeBaseController;
import com.javaee.entity.Board;

import com.javaee.service.admin.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static java.time.LocalDateTime.now;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mo
 * @since 2024-11-27
 */
@Controller
@RequestMapping("/admin")
public class BoardController extends BeforeBaseController {
    @Autowired
    private BoardService boardService;
    @RequestMapping("/toAddBoard")
    public String toAddBoard(){
        return "/admin/addBoard";
    }
    @PostMapping("/addBoard")
    public String addBoard(Board board) {
        boardService.insertBoard(board);
        return "redirect:/admin/boardList";
    }
    @RequestMapping("/boardList")
    public String boardList(String keyword,Model model, Integer currentPage) {
        if(keyword == null){
        keyword = "";
        }
        if (currentPage == null) {
            currentPage = 1;
        }
        int totalCount = boardService.selectCount();
        System.out.println("totalCount = " + totalCount);
        int pageSize = 5;
        int totalPage = (int)Math.ceil(totalCount*1.0/pageSize);
        List<Board> boards = boardService.searchBoard(keyword,(currentPage-1)*pageSize, pageSize);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("announcements", boards);
        return "/admin/boardList";
    }
    @RequestMapping("/deleteBoard")
    @ResponseBody
    public String deleteBoard(Integer id,Model model) {
            return boardService.deleteBoard(id) ? "成功" : "失败";
    }
    //修改公告
    @GetMapping("/toUpdateBoard/{id}")
    public String toUpdateBoard(@PathVariable("id") Integer id, Model model) {
        Board board = boardService.getBoardById(id);
        model.addAttribute("board", board);
        return "/admin/updateBoard";
    }
    @PostMapping("/updateBoard")
    public String updateBoard(Board board) {
        if (boardService.updateBoard(board)){
            return "redirect:/admin/boardList";
        }
        else {
            return "redirect:/admin/toUpdateBoard/"+board.getId();
        }
    }


}
